﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Windows.Networking.NetworkOperators;

namespace WlanAutoOpen
{
    public class AutoRunProxy
    {
        private static AutoRunProxy instance;
        private static readonly object lockObject = new object();
        private Thread thread;
        private bool isRunning = false;

        public event Action doWorkEvent=null;
        
        private AutoRunProxy() { }
        public static AutoRunProxy Instance()
        {
            lock (lockObject)
            {
                if (instance == null)
                {
                    instance = new AutoRunProxy();
                }
            }
            return instance;
        }
        public void Start(int times=-1)
        {
            if (!isRunning)
            {
                isRunning = true;
                thread = new Thread(new ParameterizedThreadStart(DoWork));
                thread.IsBackground = true;
                thread.Start(times);
            }
        }
        public void Stop()
        {
            isRunning = false;
            if (thread != null)
            {
                thread.Abort();
                thread = null;
            }

        }
        private void DoWork(object times)
        {
            int index = (int)times;
            if (index == -1)
            {
                while (isRunning)
                {
                    if(doWorkEvent!=null) doWorkEvent();
                    Thread.Sleep(5000);
                }
            }
            else
            {
                for(int i = 0; i < index; i++)
                {
                    if (doWorkEvent != null) doWorkEvent();
                    Thread.Sleep(5000);
                }
                Stop();
            }
            
        }

        
    }
}
